<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of SignalsHelper
 *
 * @author QuangKhoi
 */
class SignalsHelper {
    //put your code here
    public static function getSpike($_filter) {
        if ($_filter["streamId"] == '' || $_filter["dateFrom"] == '' || $_filter["dateTo"] == '') {
            return;
        }
        $language = 2;
        $stream = Stream::withId($_filter["streamId"]);
        $streamController = new StreamController($stream, new StreamView());
        $zTrendReader = new ZTrendReader($_filter["dateFrom"], $_filter["dateTo"], 7, $stream->query, $language);
        try {
            $zTrendCollection = $zTrendReader->read();
        } catch (Exception $e) {
            echo '<script>showError("#progress", ', json_encode($e->getMessage()), ');</script>';
            exit;
        }
        $spikeAt = 0;
        $items = $zTrendCollection->getItems();
        for($i = 0; $i < count($items); $i++) :
            $item = $items[$i];
            $d = $item->getDate();
            $date[] = $d->format('M d');
            $data[] = $item->getTrend();
            if ($i > 0) {
                $prevItem = $items[$i - 1];
                if ($prevItem->getTrend() > 0) {
                    if ($item->getTrend() / $prevItem->getTrend() > 1.5) {
                        $dt['value'] = $item->getTrend() / $prevItem->getTrend() - 1;
                        $j = $i - 6;
                        $dt['trend'] = array();
                        $dt['spike'] = array();
                        $dt['date'] = array();
                        if ($j < 0) $j = 0;
                        $dt['date'] = array_slice($date, $j ,$i - $j + 1, true);
                        for ($t = $j; $t <= $i; $t++) {
                            $dt['trend'][] = $items[$t]->getTrend();
                            if ($t >= $i - 1)
                                $dt['spike'][] = $items[$t]->getTrend();
                            else
                                $dt['spike'][] = null;
                        }
                        //$dt['trend'] = implode(',', $dt['trend']);
                        //$dt['spike'] = implode(',', $dt['spike']);
                        //$dt['date'] = implode(',', $dt['date']);
                        $spike[] = $dt;
                    }
                }
                else {
                    
                }
            }
        endfor;
        $result["date"] = $date;
        $result["trend"] = $data;
        $result["total"] = array_sum($data);
        $result["spike"] = $spike;
        
        return $result["spike"];
    }
}

?>
